<?php
namespace Modules\Auth\Http\Controllers;
use App\Http\Controllers\Controller;
use Modules\Auth\Models\User;
use Modules\Auth\Http\Resources\UserResource;
use Illuminate\Http\Request;

class UserController extends Controller{
    // 获取用户列表（分页 + Resource + 统一 JSON）
    public function index(Request $request){
/** @var \Modules\Auth\Models\User $user */
        //auth()是全局辅助函数
        //auth()->user()获取当前登录用户，
        //auth('api'):Config\auth.php中定义的api guard，此处使用了sanctum
        $user = auth('api')->user();
        //检查用户是否有users.index权限 can()爆红因为模型的间接继承，不影响使用
        $check=$user->can('users.index');
        if (!$check) {
            return response()->json(['status' => 'error', 'message' => '权限不足'], 403);
        }
        //下方为原本代码
        $perPage = $request->get('per_page', 5);
        $name = $request->get('name');
        $email = $request->get('email');
        $users = User::when($name, fn($q) => $q->where('name', 'like', "%{$name}%"))
                    ->when($email, fn($q) => $q->where('email', 'like', "%{$email}%"))
                    ->paginate($perPage);
        // Laravel 自动带 links 和 meta
        return UserResource::collection($users);
    }

    // 获取单个用户
    public function show($id){
        $user=User::findOrFail($id); // 查找用户，不存在抛异常
        return response()->json(['status'=>'success','data'=>new UserResource($user)]); // 返回 JSON
    }

    // 创建用户
    public function store(Request $request){
        $data=$request->validate([ // 验证参数
            'name'=>'required',
            'email'=>'required|email',
            'password'=>'required'
        ]);
        $data['password']=bcrypt($data['password']); // 加密密码
        $user=User::create($data); // 创建用户
        return response()->json(['status'=>'success','message'=>'User created','data'=>new UserResource($user)]);
    }

    // 更新用户
    public function update(Request $request,$id){
        $user=User::findOrFail($id); // 查找用户
        $data=$request->validate([ // 验证参数，可选更新
            'name'=>'sometimes',
            'email'=>'sometimes|email',
            'password'=>'sometimes'
        ]);
        if(isset($data['password'])) $data['password']=bcrypt($data['password']); // 加密密码
        $user->update($data); // 更新
        return response()->json(['status'=>'success','message'=>'User updated','data'=>new UserResource($user)]);
    }

    // 删除用户
    public function destroy($id){
        User::findOrFail($id)->delete(); // 删除用户
        return response()->json(['status'=>'success','message'=>'User deleted']);
    }

    public function lock($id){
        $user=User::findOrFail($id); // 查找用户
        $user->is_locked = $user->is_locked == 0 ? 1 : 0;
        $user->save();
        return response()->json([
            'status' => 'success',
            'message' => $user->is_locked ? 'User locked' : 'User unlocked',
            'data' => new UserResource($user)
        ]);
    }
}
